import jwt
from fastapi import APIRouter, Depends, HTTPException
from passlib.context import CryptContext
from starlette import status

from app.core import user as user_service
from app.models.authentication import TokenDto, TokenReq, UserInfo
from app.models.common import ResultDto, success

router = APIRouter(
    prefix="/auth",
    tags=["Authentication"]
)

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def create_access_token(user_info: UserInfo):
    return jwt.encode(user_info.model_dump(), "ppMmF8X0IJIX/XR263IlCHe4mgJA5dnrY/qsQbWy5Q1sgM1Z8WE7WC7SI8ujyqg4+m2gx892BxXgy/wfGJ1f0w==", algorithm="HS256")

@router.post("/token")
async def get_token(token_req: TokenReq) -> ResultDto:
    user = user_service.get_by_login_name(token_req.username)
    if user and pwd_context.verify(token_req.password, user.password):
        user_info = UserInfo(**user.model_dump())

        token_dto = TokenDto(
            access_token=create_access_token(user_info),
            refresh_token=create_access_token(user_info),
            user_info=user_info)
        return success(token_dto)
    else:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )


@router.post("/refresh")
async def refresh():
    return {}

@router.post("/logout")
async def refresh():
    return {}
